package com.xy6.dpdemo.book.delegate.task;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 任务执行器委托类。实现拦截运行方法，执行记录日志方法
 * 
 * @author zhang
 * @since 2018-04-29
 */
public class TaskExecuterDelegator implements InvocationHandler {

	private TaskExecuter originObj;
	
	/**
	 * 创建代理对象。调用代理对象的方法时，jdk会执行invoke方法，实现拦截
	 * 
	 * @param obj
	 * @return
	 */
	public ITaskExecuter createProxy(TaskExecuter obj){
		this.originObj = obj;
		return (ITaskExecuter) Proxy.newProxyInstance(originObj.getClass().getClassLoader(), originObj.getClass()
				.getInterfaces(), this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;
		if("run".equals(method.getName())){
			Method[] methods = originObj.getClass().getMethods();
			Method before = null;
			Method after = null;
			for(Method elem : methods){
				if("beforeRun".equals(elem.getName())){
					before = elem;
					break;
				}
			}
			for(Method elem : methods){
				if("afterRun".equals(elem.getName())){
					after = elem;
					break;
				}
			}
			if(null != before){
				before.invoke(originObj, args);
			}
			result = method.invoke(originObj, args);
			if(null != after){
				after.invoke(originObj, args);
			}
		} else {
			result = method.invoke(originObj, args);
		}
		return result;
	}

}
